<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>设置代理条件</title>
    <#include "/pubHeadStyle.html">
</head>
<body>
    <div style="height: 100%;overflow: auto;">
        <a class="layui-btn layui-btn-sm" id="addRuleSz" data-method="addRuleSz" style="margin: 10px 0 0 10px;">添加</a>

    </div>
    <!--<div class="layui-btn-container" style="text-align: center;position: absolute;bottom: 5px;left: 0px;right: 0px;">-->
    <!--<button class="layui-btn" lay-submit lay-filter="varForm" id="save">保存</button>-->
    <!--<button class="layui-btn layui-btn-danger" id="close">关闭</button>-->
    <!--</div>-->

    <!--三个及以上个 弹窗时启用的-->
    <div id="windowUrls" style="display: none"></div>
    <script id="addSettings" type="text/html">
        <fieldset style="margin: 5px 2px 5px 2px;" zone="team" class="returnDiv" >
                    <legend><span>规则设置</span><span class="layui-badge delBadge" style="margin-left: 10px;cursor: pointer;">删除</span></legend>
                    <div class="table-top">
                            <div class="layui-row" style="border: 1px solid #ccc;margin-bottom: 10px;">
                                    <div class="layui-col-md2">
                                            <label class="layui-form-label" style="text-align: right;line-height: 38px;">代理人：</label>
                                        </div>
                                    <div class="layui-col-md4">
                                                <input type="hidden" name="agentid" class="layui-input"><input type="hidden" name="tableId" class="layui-input" value="${tableId}">
                                                <input readonly="readonly" type="text" name="agent" class="layui-input" style="margin-top: 10px;">
                                        </div>
                                    <div class="layui-col-md4">
                                                <a class="authnameXz layui-btn layui-btn-sm" style="margin: 13px 0 0 10px;"><span>选择...</span></a>
                                        </div>
                                </div>
                            <div class="table-top-right" style="float: right">
                                    <div class="layui-btn-container" >
                                            <a class="layui-btn layui-btn-sm addRule" data-method="addRule">添加规则</a>
                                            <a class="layui-btn layui-btn-sm addDivf">添加脚本</a>
                                            <a class="layui-btn layui-btn-danger layui-btn-sm theDelRules" >删除</a>
                                        </div>
                                </div>
                            <div style="clear: both"></div>
                        </div>
                    <div class="ruleDiv" style="border:2px solid #ccc;margin:5px 0 0 0;"></div>
                </fieldset>
    </script>
    <script id="ruleStr" type="text/html">
        <div class="layui-form-item" style="padding: 5px 0;border: 1px solid #C0C4CC; position:relative;height: 37px; width: 90%;margin: 4px 0 4px 4px">
            <span style="display: none;border-right: 1px solid #555;position: absolute;top: -30px;right: -30px;height: 10px;"></span>
            <span style="display: none;border-right: 1px solid #555;position: absolute;top: 0px;right: -30px;height: 15px;"></span>
            <span style="display: none;border-top: 1px solid #555;position: absolute;top: -30px;right: -30px;width: 30px;"></span>
            <span style="display: none;border-top: 1px solid #555;position: absolute;top: 14px;right: -30px;width: 30px;"></span>
            <select style="display: none;position: absolute;top: -20px;right: -50px;" class="compTypeSel">
                <option value="and">且</option>
                <option value="or">或</option>
            </select>
            <input name='RulesCK' style='float: left;margin: 13px 0 0 10px;' type="checkbox">
            <div style="float: left">
                <label class="layui-form-label" ruleType="1">普通规则</label>
                <div class="layui-input-block" style="line-height: 36px;">
                    <select name="city" lay-verify="required" style='vertical-align: middle;height: 38px;border-color: #D2D2D2!important;' class='someRule'>
                        <option value="0">--请选择--</option>
                        <option value="" disabled="disabled">表单变量</option>
                        <option value="startUser"    id='startUser'>发起人ID</option>
                        <option value="businessKey"  id='businessKey'>表单主键</option>
                        <option value="flowRunId"      id='flowRunId'>流程运行ID</option>
                        <#if bpmDefVars?? >
                        <option value="" disabled="disabled">自定义变量</option>
                        <#list bpmDefVars as var>
                        <option value= ${var.varKey} id=${var.varDataType}>${var.varName}</option>
                    </#list>
                </#if>
                </select>
            </div>
        </div>
        <div style="margin-top: -6px;display: none" class="holiday" opttype="1">
            <div class="layui-input-block" style="margin-left: 4px; float: left">
                <select name="city" lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;'>
                    <option value="==" >等于</option>
                    <option value="!=">不等于</option>
                    <option value=">">大于</option>
                    <option value="<">小于</option>
                    <option value=">=">大于等于</option>
                    <option value="<=">小于等于</option>
                </select>
            </div>
            <input type="text" name="title" required  lay-verify="required" autocomplete="off" class="layui-input" style="width: 120px;height: 38px;border-color: #D2D2D2!important;float: left">
            <div class="layui-input-block" style='margin-left: 4px; float: left'>
                <select name="city" lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;' >
                    <option value="==" >等于</option>
                    <option value="!=">不等于</option>
                    <option value=">">大于</option>
                    <option value="<">小于</option>
                    <option value=">=">大于等于</option>
                    <option value="<=">小于等于</option>
                </select>
            </div>
            <input type="text" name="title" required  lay-verify="required" autocomplete="off" class="layui-input" style="width: 120px;height: 38px;border-color: #D2D2D2!important;margin-top: 6px">
        </div>
        <div style="margin-top: -6px;display: none" class="holiday" opttype="3">
            <div class="layui-input-block" style="margin-left: 4px; float: left">
                <select name="city" class='selectOne' lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;'>
                    <option value="==" >等于</option>
                    <option value="!=">不等于</option>
                    <option value=">">大于</option>
                    <option value="<">小于</option>
                    <option value=">=">大于等于</option>
                    <option value="<=">小于等于</option>
                </select>
            </div>
            <input type="text" name="title" required  lay-verify="required" autocomplete="off" class="layui-input" id='oneDate{{ d.nam }}' placeholder='yyyy-MM-dd' style="width: 120px;height: 38px;border-color: #D2D2D2!important;float: left">
            <div class="layui-input-block" style='margin-left: 4px; float: left'>
                <select name="city" lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;' >
                    <option value="==" >等于</option>
                    <option value="!=">不等于</option>
                    <option value=">">大于</option>
                    <option value="<">小于</option>
                    <option value=">=">大于等于</option>
                    <option value="<=">小于等于</option>
                </select>
            </div>
            <input type="text" name="title" required  lay-verify="required" autocomplete="off" class="layui-input" id='twoDate{{ d.nam }}' placeholder='yyyy-MM-dd' style="width: 120px;height: 38px;border-color: #D2D2D2!important;margin-top: 6px">
        </div>
        <div style="display: none;margin-top: -6px" class="startID" opttype="5">
            <div class="layui-input-block" style="margin-left: 4px; float: left">
                <select name="city" lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;'>
                    <option value="contains()" >包含</option>
                    <option value="noContains()">不包含</option>
                </select>
            </div>
            <input type="hidden" name="startUserId" style="float: left">
            <input type="text" name="title" required  readonly="readonly" lay-verify="required" autocomplete="off" class="layui-input" style="width: 120px;height: 38px;border-color: #D2D2D2!important;float: left">
            <button class="layui-btn layui-btn-xs selectUser" style='margin: 15px 0 0 10px;'>选择</button>
        </div>
        <div style="display: none;margin-top: -6px" class= "formID" opttype="2">
            <div class="layui-input-block" style="margin-left: 4px; float: left">
                <select name="city" lay-verify="required" style='height: 38px;border-color: #D2D2D2!important;'>
                    <option value="equals()" >完全等于</option>
                    <option value="!=">不等于</option>
                    <option value="equalsIgnoreCase()">等于（忽略大小写）</option>
                    <option value="contains()">包含</option>
                    <option value="noContains()">不包含</option>
                </select>
            </div>
            <input type="text" name="title" required  lay-verify="required" autocomplete="off" class="layui-input" style="width: 120px;height: 38px;border-color: #D2D2D2!important;float: left">
        </div>
        </div>
    </script>
    <script id="scriptStr" type="text/html">
        <div class="layui-form-item" style="border: 1px solid #C0C4CC;position: relative; height: 37px; width: 90%;margin: 4px 0 4px 4px;padding: 5px 0;">
            <span style="display: none;border-right: 1px solid #555;position: absolute;top: -30px;right: -30px;height: 10px;"></span>
            <span style="display: none;border-right: 1px solid #555;position: absolute;top: 0px;right: -30px;height: 15px;"></span>
            <span style="display: none;border-top: 1px solid #555;position: absolute;top: -30px;right: -30px;width: 30px;"></span>
            <span style="display: none;border-top: 1px solid #555;position: absolute;top: 14px;right: -30px;width: 30px;"></span>
            <select style="display: none;position: absolute;top: -20px;right: -50px;" class="compTypeSel">
                <option value="and">且</option>
                <option value="or">或</option>
            </select>
            <input name='RulesCK' style='float: left;margin: 13px 0 0 10px;' type="checkbox">
            <label class="layui-form-label" ruleType="2">脚本规则</label>
            <textarea class="script-add-role theJiaoben" style='float: left;display:none;'></textarea>
            <button class="layui-btn layui-btn-xs addDivz" style="margin: 7px 0 0 10px;">脚本</button>
        </div>
    </script>
    <script>
        var assignUseType=0;
        function changeLoad(url){
            $("#ruleDiv").load(url);
        }
        function sortTr(obj,up){
            var thisTr = $(obj).parents("tr");
            if(up){
                var prevTr = $(thisTr).prev();
                if(prevTr){
                    thisTr.insertBefore(prevTr);
                }
            } else {
                var nextTr = $(thisTr).next();
                if(nextTr){
                    thisTr.insertAfter(nextTr);
                }
            }
        };
        layui.config({
            base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
        }).extend({
            index: 'index' //主入口模块
        }).use(['index','layer', 'table', 'element','setter','form','jquery','laytpl','laydate','commons'], function(){
            var layer = layui.layer
                ,table = layui.table
                ,element = layui.element
                ,setter = layui.setter
                ,form=layui.form
                ,$ = layui.jquery
                ,laytpl = layui.laytpl
                ,commons = layui.commons
                ,laydate = layui.laydate;
            var modelId = "${modelId}";
            //添加规则设置的点击事件
            $("#addRuleSz").click(function () {
                addRuleSz();
            });

            //添加规则设置的公共方法
            function addRuleSz(){
                //渲染模版
                var data = { //数据
                }
                var setTpl = addSettings.innerHTML
                    ,view = $("#addRuleSz").parent('div');
                laytpl(setTpl).render(data, function(html){
                    view.append(html);
                });
            }
            //删除
            $(document).on("click",".delBadge",function(){
                $(this).parents('fieldset').remove();
            });
            //全局使用。即所有弹出层都默认采用，但是单个配置skin的优先级更高
            layer.config({
                skin: 'btn-class'
            })
            $(document).on("click",".authnameXz",function(){
                var userSelectorWin;
                var body;
                var that = $(this);
                parent.layer.open({
                    type: 2,
                    title: '人员选择器',
                    area: ['760px','630px'],
                    btn:["保存","取消","撤销"],
                    content:serverPath.systemPath + setter.sysLinkPath+ "dialog/view/singleSysUserDialog",
                    success: function(layero, index){
                        body = parent.layer.getChildFrame('body',index);
                        userSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                    },
                    yes:function (index,layero) {
                        //执行iframe页的save方法
                        userSelectorWin.saveData(index);
                        var theUserList = body.find("input[name=selectUser]").val();
                        if (theUserList) {
                            var item = JSON.parse(theUserList);
                            var userId = item.userId;
                            var userName = item.fullName;
                            that.parent().prev().find("input[name='agentid']").val(userId);
                            that.parent().prev().find("input[name='agent']").val(userName);
                        }
                        parent.layer.close(index);
                    },
                    btn3:function (index, layero) {
                        userSelectorWin.cancelData(index);
                        return false //开启该代码可禁止点击该按钮关闭
                    }
                })
            });
            //添加规则
            var nam = 1;
            function addRuleStr(that){
                //渲染模版
                var data = { //数据
                    "nam" : nam
                }
                var getTpl = ruleStr.innerHTML
                    ,view = that.parent().parent().parent().siblings('.ruleDiv');
                laytpl(getTpl).render(data, function(html){
                    view.append(html);
                });
                laydateGZ();
                nam++;
            };
            //添加规则触发事件
            $(document).on("click",".addRule",function(){
                addRuleStr($(this));
                showConnect($(this));
                someRuleChange($(this));
            });
            //监听ruleDiv发生变化
            $(document).on("click",".selectUser",function(){
                // layer.alert('只想简单的提示');
                var userSelectorWin;
                var body;
                var itemName='';
                var itemId='';
                var that = $(this).prev();
                var thatHidden = $(this).prev().prev();
                // parent.
                parent.layer.open({
                    type:2
                    ,title:'人员选择器'
                    ,area:['980px','630px']
                    ,btn:["保存","取消","撤销"]
                    ,resize:false
                    ,content: serverPath.systemPath + setter.sysLinkPath+'dialog/view/sysUserDialog'
                    ,success: function(layero, index){
                        body = parent.layer.getChildFrame('body',index);
                        userSelectorWin = parent.window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        //向用户选择器页面传递初始值[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                        if (that.val()) {
                            userSelectorWin.layui.userList = [];
                            var hiddenDataArr = thatHidden.val().split(",");
                            var theDataArr = that.val().split(",");
                            $.each(hiddenDataArr,function (k,v) {
                                var userListObj={};
                                userListObj.name = theDataArr[k];
                                userListObj.userId = v;
                                userSelectorWin.layui.userList.push(userListObj);
                            })
                        }
                    },
                    yes:function(index,layero){
                        var theUserList = body.find("input[name=userList]").val();
                        if (theUserList){
                            //用户选择器返回的选择人员数组[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                            $.each(JSON.parse(theUserList),function (index, item) {
                                itemName += item.name + ",";
                                itemId += item.userId + ",";
                            });
                            if (itemName.length > 0) {
                                itemName = itemName.substr(0,itemName.length - 1);
                                itemId = itemId.substr(0,itemId.length - 1);
                            }
                            that.val(itemName);
                            thatHidden.val(itemId);
                        }
                        parent.layer.close(index);

                    },
                    btn3:function(index, layero){
                        userSelectorWin.cancelData(index);
                        return false //开启该代码可禁止点击该按钮关闭
                    }
                });
            })
            function showConnect(that) {
                var divlangth = that.parent().parent().parent().siblings('.ruleDiv').children('div');
                if (divlangth.length>1){
                    for (var i=0;i<divlangth.length;i++) {
                        if (i!==0){
                            divlangth.eq(i).children("span").show();
                            divlangth.eq(i).children("select").show();
                        }else {
                            divlangth.children("span").hide();
                            divlangth.children("select").hide();
                        }
                    }
                }else {
                    divlangth.children("span").hide();
                    divlangth.children("select").hide();
                }
            };

            /**
             * 规则设置的判断区间
             * [optType ='1']  等于、不等于、大于、小于、大于等于、小于等于               自定义变量：数字；流程运行ID
             * [optType ='2']  完全等于、不等于、等于（忽略大小写）、包含、不包含          自定义变量：字符串；表单主键
             * [optType ='3']  （时间格式） 等于、不等于、大于、小于、大于等于、小于等于   自定义变量：日期
             * [optType ='4']  等于、不等于、包含、不包含
             * [optType ='5']  包含、不包含                                              发起人ID
             */
            function someRuleChange(){
                $('.someRule').change(function () {
                    ruleChange(this);
                })
            };

            //普通规则改变触发事件
            function ruleChange(element) {
                var optionId = $("option:selected",element).attr("id");
                if (optionId == "flowRunId" || optionId == "number") {
                    $(element).parent().parent().siblings("[optType ='2']").hide();
                    $(element).parent().parent().siblings("[optType ='5']").hide();
                    $(element).parent().parent().siblings("[optType ='3']").hide();
                    $(element).parent().parent().siblings("[optType ='1']").show().addClass('flowRunId');
                    // optTypeFunc();
                } else if (optionId == "startUser") {
                    $(element).parent().parent().siblings("[optType ='1']").hide();
                    $(element).parent().parent().siblings("[optType ='2']").hide();
                    $(element).parent().parent().siblings("[optType ='3']").hide();
                    $(element).parent().parent().siblings("[optType ='5']").show().addClass('startUser');
                } else if (optionId == "businessKey" || optionId == "varchar") {
                    $(element).parent().parent().siblings("[optType ='1']").hide();
                    $(element).parent().parent().siblings("[optType ='5']").hide();
                    $(element).parent().parent().siblings("[optType ='3']").hide();
                    $(element).parent().parent().siblings("[optType ='2']").show().addClass('businessKey');
                } else if (optionId == "date"){
                    $(element).parent().parent().siblings("[optType ='2']").hide();
                    $(element).parent().parent().siblings("[optType ='5']").hide();
                    $(element).parent().parent().siblings("[optType ='1']").hide();
                    $(element).parent().parent().siblings("[optType ='3']").show().addClass('date');
                }else {
                    $(element).parent().parent().siblings("[optType ='1']").hide();
                    $(element).parent().parent().siblings("[optType ='2']").hide();
                    $(element).parent().parent().siblings("[optType ='3']").hide();
                    $(element).parent().parent().siblings("[optType ='5']").hide();
                }
            };
            //设置
            function laydateGZ(){
                laydate.render({
                    elem: '#oneDate'+nam, //指定元素
                });
                laydate.render({
                    elem: '#twoDate'+nam, //指定元素
                    // min: minStr,
                    // max: maxStr
                });
            }

            //添加脚本的点击事件
            $(document).on("click",".addDivf",function(){
                // changeLoad("/workflow/bpmNodeUser/view/addScript?modelId="+modelId);
                // $('#ruleDiv').append(txt1)
               addDivf($(this),true);
            });

            //添加脚本的公共方法
            function  addDivf(that,isReturn){
                //渲染模版
                var data = { //数据
                }
                var scriptTpl = scriptStr.innerHTML
                    ,view = that.parent().parent().parent().siblings('.ruleDiv');
                laytpl(scriptTpl).render(data, function(html){
                    view.append(html);
                });

                showConnect(that);
                //是否启用脚本弹出层
                if(isReturn) {
                    scriptClick(that);
                }
            }

            //脚本弹出层
            function scriptClick(that) {
                parent.layer.open({
                    title:'脚本',
                    type: 2,
                    shade: 0.3,
                    btn:["保存","关闭"],
                    skin: 'btn-class',
                    area: ['80%', '90%'],
                    content: serverPath.workflowPath + setter.workflowLinkPath +'bpmNodeUser/view/script?modelId='+modelId,
                    // content: $('#windowUrls')
                    yes:function (index,layero) {
                        //获取iframe的body元素
                        var body = parent.layer.getChildFrame('body',index);
                        //得到iframe页的窗口对象
                        var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                        //执行iframe页的showMsg方法
                        var theDiv = iframeWin.frames[0].document.children[0].getElementsByClassName("editbox")[0].innerText;
                        that.parent().parent().parent().siblings('.ruleDiv').find(".theJiaoben").html(theDiv);
                        that.parent().parent().parent().siblings('.ruleDiv').find(".theJiaoben").removeClass("theJiaoben");
                        parent.layer.close(index);
                    }
                    // });
                });
            };
            $(document).on("click",".addDivz",function(){
                $(this).prev().addClass("theJiaoben");
                var that = $(this);
                var data = $(this).prev().text();
                parent.layer.open({
                    title:'脚本',
                    type: 2,
                    shade: 0.3,
                    btn:["保存","关闭"],
                    skin: 'btn-class',
                    area: ['80%', '90%'],
                    content:serverPath.workflowPath + setter.workflowLinkPath +'bpmNodeUser/view/script?modelId='+modelId+'&data='+data,
                    yes:function (index,layero) {
                        //获取iframe的body元素
                        var body = parent.layer.getChildFrame('body',index);
                        //得到iframe页的窗口对象
                        var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                        var theDiv = iframeWin.frames[0].document.children[0].getElementsByClassName("editbox")[0].innerText;
                        that.prev().html(theDiv);
                        that.prev().removeClass("theJiaoben");
                        parent.layer.close(index);
                    }

                });
            })

        //规则删除
        $(document).on("click",".theDelRules",function(){
            var that = $(this);
            var cks=$(this).parent().parent().parent().siblings('.ruleDiv').find('input[name=RulesCK]:checked')
                // $("#ruleDiv input[name=RulesCK]:checked");
            if(cks.length==0){
                layer.confirm('请选择删除的规则！', {
                    btn: "确定"
                    , title: '提示信息'
                    , yes: function () {
                        layer.close(layer.index);
                    }
                });
                return ;
            }
            layer.confirm('确定要删除所选项吗?', {icon: 3, title:'提示'}, function(index){
                //do something
                for(var i=cks.length-1;i>=0;i--) {
                    $(cks[i]).parent().remove();
                }
                layer.close(index);
                showConnect(that);
            });

            })

            //保存
            window.save = function () {
                var param=eval("("+$("#conditionEntity").val()+")");

                var users=extractNodeUserDatas();
                if(!users){
                    layer.alert("没有设置用户!","提示信息");
                    return
                }else{
                    param.users=JSON.stringify(users);
                }
                assignUseType=param.conditionType;

                var conditionShow = [];
                $("#tbodyUserSet tr").each(function() {
                    conditionShow.push($('select[name="assignType"] option:selected',$(this)).text()+":"+$(".textarea", $(this)).val());
                });
                if(conditionShow){
                    param.conditionShow=conditionShow.join(",");
                }
                var parentProcDefId = $("input[name='parentProcDefId']").val();
                if(parentProcDefId){
                    param.parentProcDefId=parentProcDefId;
                }
                //规则设置
                var condition = [];
                $("#ruleDiv .layui-form-item").each(function(index){
                    //公共属性：规则关系compType
                    var compType=$(this).find(".compTypeSel").val();

                    var _rule = $(".someRule",this);
                    var obj1 = {};
                    var str ;
                    if(_rule.val()){
                        var flowvarKey    = _rule.val();
                        var optType ;
                        var conDesc = $("option:selected",_rule).text();
                        var judgeCon1,judgeCon2;
                        var judgeVal1,judgeVal2;
                        $(_rule).parent().parent().nextAll("div").each(function(){
                            var _this = $(this);
                            if(!_this.is(":hidden")) {
                                //todo 融合表单后，动态生成下拉框时修改判断条件
                                if(flowvarKey=="startUser"){
                                    optType   = _this.attr("opttype");
                                    judgeCon1 = $("select",_this).val();
                                    judgeVal1 = $("input[name='title']",_this).val()+"&&"+$("input[name='startUserId']",_this).val();
                                    conDesc  += "  "+$("select option:selected",_this).text()+$("input[name='title']",_this).val();
                                }else if(flowvarKey=="businessKey"){
                                    optType   = _this.attr("opttype");
                                    judgeCon1 = $("select",_this).val();
                                    judgeVal1 = $("input",_this).val();
                                    conDesc  += "  "+$("select option:selected",_this).text()+$("input",_this).val();
                                }else{
                                    optType   = _this.attr("opttype");
                                    var strCon1,strCon2;
                                    $("select",_this).each(function (index) {
                                        if(index==0) {
                                            judgeCon1 = $(this).val();
                                            strCon1   = $("option:selected",this).text();
                                            return ;
                                        }
                                        judgeCon2=$(this).val();
                                        strCon2   = $("option:selected",this).text();
                                    });
                                    $("input",_this).each(function (index) {
                                        if(index==0) {
                                            judgeVal1 = $(this).val();
                                            conDesc  += ("  "+strCon1+"  "+$(this).val());
                                            return ;
                                        }
                                        judgeVal2=$(this).val();
                                        conDesc  += ("  "+strCon2+"  "+$(this).val());
                                    })

                                }
                            }
                        });
                        obj1.optType=optType;
                        obj1.flowvarKey=flowvarKey;
                        obj1.judgeCon1=judgeCon1;
                        obj1.judgeVal1=judgeVal1;
                        if(judgeCon2!=null) {
                            obj1.judgeCon2 = judgeCon2;
                            obj1.judgeVal2 = judgeVal2;
                        }
                        obj1.conDesc=conDesc;
                        obj1.ruleType=1;
                        obj1.compType=compType;

                    }else{
                        obj1.script=$(".script-add-role",this).val();
                        obj1.conDesc="脚本";
                        obj1.ruleType="2";
                        obj1.compType=compType;
                    }
                    condition.push(obj1);
                });
                param.condition=JSON.stringify(condition);
                param.nodeId    = "${nodeId}";
                param.procDefId = "${actDefModel.procDefId}";
                $.ajax({
                    url:serverPath.workflowPath+setter.workflowLinkPath+"bpmUserCondition/save"
                    ,method:'post'
                    ,data:param
                    ,dataType:'json'
                    ,success:function (res) {
                        if(commons._filterRecord(res)) {
                            layer.msg(res.msg, {icon: 6, time: 1000})
                        }else {
                            layer.msg(res.msg, {icon: 5, time: 1000})
                        }
                    }
                })
            };

            // 获取用户设置
            function extractNodeUserDatas(){
                var users = [];
                // var users;
                $("#tbodyUserSet tr").each(function(index){
                    var tr = $(this);
                    var nodeId      =   $("input[name='nodeId']").val();
                    var nodeUserId  =   $("input[name='modelId']").val();
                    var assignType  =   $('select[name="assignType"]',$(this)).val();
                    var cmpIds      =   $(".hiddenJson",$(this)).val();
                    var cmpNames    =   $(".textarea",$(this)).val();
                    var extractUser =   $('select[name="extractUser"]',$(this)).val();
                    var compType    =   $('select[name="compType"]',$(this)).val();

                    var user={
                        nodeUserId:nodeUserId,
                        assignType:assignType,
                        assignUseType:assignUseType,
                        nodeId:nodeId,
                        cmpIds:cmpIds,
                        cmpNames:cmpNames,
                        compType:compType,
                        extractUser:extractUser
                    };
                    users.push(user);
                });
                if(users.length==0){
                    return false;
                }
                // return users;
                return users;
            };
            //回显
            var _id="${id}";
            if(_id) {
                $.ajax({
                    url: serverPath.workflowPath  + setter.workflowLinkPath + 'agentSetting/getAgentCondition',
                    method: 'post',
                    data: {id:_id},
                    dataType: 'json',
                    success: function (res) {
                        if( (res.code==0 || res.code=='0') && res.data){
                            //有回显值，进行回显处理
                            returnCondition(res.data);
                        }else{
                            //没有回显值，添加一条空白规则设置
                            addRuleSz();
                        }
                    }
                });
            }else{
                //自执行，添加一条空白规则设置
                addRuleSz()
            };

            /**
             * 循环遍历data数据进行回显：
             *      1、是否添加规则设置（第一条数据不用添加）
             *      2、代理人
             *      3、规则回显
             *      4、将 .returnDiv 去除，便于下一条数据回显
             */
            function returnCondition(data) {
                for(var i=0;i<data.length;i++){
                    //1、新增规则设置
                    addRuleSz()

                    //2、代理人
                    $(".returnDiv input[name=agent]").val(data[i].agent);
                    $(".returnDiv input[name=agentid]").val(data[i].agentId);

                    //3、规则回显（必须在.returnConditionDiv的下面）
                    var conditionStr= data[i].condition;
                    if(conditionStr){
                        var ruleArr = JSON.parse(conditionStr).condition;
                        for(var j=0;j<ruleArr.length;j++) {
                            var _json = ruleArr[j];
                            if (_json.script) {

                                //脚本规则 theJiaoben
                                addDivf($(".returnDiv .addDivf"),false);
                                // $('.returnDiv #ruleDiv').append(scriptStr);
                                $('.returnDiv .ruleDiv .addScript').each(function (index) {
                                    var _script = ($(this).text()) ;
                                    if (_script || _script=='') {
                                        $(this).text(_json.script);
                                    }
                                    $(this).siblings(".compTypeSel").val(_json.compType);
                                    $(this).removeClass("addScript");
                                });
                            } else {
                                //普通规则
                                addRuleStr($(".returnDiv .addRule"));
                                $('.returnDiv .ruleDiv .someRule').each(function () {
                                    var _this = $(this);
                                    if (_this.val() == 0) {
                                        _this.val(_json.flowvarKey);
                                        someRuleChange();
                                        ruleChange(this);
                                        showConnect($(".returnDiv .addRule"));
                                        _this.parents(".layui-form-item").find(".compTypeSel").val(_json.compType);
                                        $(_this).parent().parent().nextAll("div").each(function () {
                                            var _element = $(this);
                                            if (!_element.is(":hidden")) {
                                                $("select", _element).each(function (index) {
                                                    if (index == 0) {
                                                        $(this).val(_json.judgeCon1);
                                                        return;
                                                    }
                                                    $(this).val(_json.judgeCon2);
                                                });
                                                $("input", _element).each(function (index) {
                                                    //发起人
                                                    if (_json.flowvarKey == "startUser") {
                                                        var _user = (_json.judgeVal1).split("&");
                                                        //发起人ID，隐藏值
                                                        $("input[name='startUserId']", _element).val(_user[0]);
                                                        //发起人姓名，显值
                                                        $("input[name='judgeVal1']", _element).val(_user[1]);
                                                        return;
                                                    }
                                                    //其他
                                                    if (index == 0) {
                                                        $(this).val(_json.judgeVal1);
                                                        return;
                                                    }
                                                    $(this).val(_json.judgeVal2);
                                                })
                                            }
                                        });
                                    }
                                });
                            }
                        }
                    }

                    //4、将 .returnConditionDiv 去除，便于下一条数据回显
                    $(".returnDiv").removeClass("returnDiv");
                }
            }

        });
    </script>

</body>
</html>